//
//  HEHealthCheckChartController.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/12/21.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEHealthCheckChartController.h"
#import "HEDataManageModel.h"
#import "HEHealthCheckRecodCell.h"
#import "BRStringPickerView.h"
#import "HEHealthDataModel.h"

@import Charts;
 
@import SwiftCus;

@interface HEHealthCheckChartController () <  ChartViewDelegate>

@property (nonatomic, strong) LineChartView *chartView;
@property (nonatomic, strong) PieChartView *pieChartView;


@property (nonatomic, strong) NSMutableArray *xAixTitles;
@property (nonatomic, strong) NSMutableArray *yValues;
@property (nonatomic, strong) UIView *chartWarp;

@property (nonatomic, strong) NSArray *lineColors;


@property (nonatomic, strong) UIScrollView *scrollView;
// 约束参照视图,也是容器视图
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) NSArray *nomarlRangs;
@property (nonatomic, strong) UIView *dataWarp;
@property (nonatomic, strong) UISegmentedControl *segment;


@property (nonatomic, strong) NSString *start_date;
@property (nonatomic, strong) NSString *end_date;
@property (nonatomic, assign) NSInteger page_number;

@property (nonatomic, strong) HEHealthDataModel *healthModel;
@property (nonatomic, strong) NSMutableArray <UILabel *>*normalLbs;

@end

@implementation HEHealthCheckChartController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.zx_navBar.hidden = YES;
    
    _page_number = 30;
    
    [self initUI];
    
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBindUser:) name:KNotificationSelectBindUser object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationSelectBindUser object:nil];
}

- (void)changeBindUser:(NSNotification *)notif {
    _selectUser = (HEBindUserModel *)notif.object;
    [_scrollView.mj_header beginRefreshing];
}

- (void)initUI {
    // 1. 添加scrollView
    [self.view addSubview:self.scrollView];
    // 2. 添加参照视图
    [self.scrollView addSubview:self.contentView];
    
    
    /**顶部视图*/
    UIView *topView = [UIView new];
    [_contentView addSubview: topView];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_contentView).offset(20);
        make.right.left.equalTo(_contentView);
    }];
    
    // 左侧数据展示
    UIView *dataWarp = [UIView new];
    _dataWarp = dataWarp;
    dataWarp.backgroundColor = KWhiteColor;
    dataWarp.layer.cornerRadius = 5;
    [topView addSubview: dataWarp];
    
    UILabel *noticeLb = [UILabel new];
    noticeLb.text = @"-- 正常范围 --";
    noticeLb.font = DYBlodFont(20);
    noticeLb.numberOfLines = 0;
    noticeLb.textColor = CNavSubTitleColor;
    [dataWarp addSubview: noticeLb];
    
    [self createBigItemWithTopView:noticeLb];
    
    // 左侧
    [noticeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(dataWarp).offset(12);
        make.left.equalTo(dataWarp).offset(10);
        make.right.equalTo(dataWarp).offset(-10);
    }];
    
    if (![@"BMI" isEqualToString: _model.check_name]) {
        // 右侧添加数据按钮
        UIView *addRecWarp = [UIView new];
        addRecWarp.backgroundColor = KWhiteColor;
        addRecWarp.layer.cornerRadius = 5;
        [topView addSubview: addRecWarp];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addRecClick)];
        [addRecWarp addGestureRecognizer: tap];
        
        [dataWarp mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topView);
            make.left.equalTo(topView).offset(20);
            make.right.equalTo(addRecWarp.mas_left).offset(-20);
            make.height.equalTo(addRecWarp.mas_height);
        }];
     
        [addRecWarp mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topView);
            make.left.equalTo(dataWarp.mas_right);
            make.right.equalTo(topView).offset(-20);
            make.bottom.equalTo(topView).offset(-20);
        }];
        [dataWarp setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
        [addRecWarp setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
        
        UIImageView *addIconView = [UIImageView new];
        addIconView.image = IMAGE_NAMED(@"fit_note_index");
        addIconView.contentMode = UIViewContentModeScaleAspectFill;
        [addRecWarp addSubview:addIconView];
        
        UILabel *addTitleLb = [UILabel new];
        addTitleLb.text = @"添加数据";
        addTitleLb.font = DYBlodFont(17);
        addTitleLb.numberOfLines = 0;
        addTitleLb.textAlignment = NSTextAlignmentCenter;
        [addRecWarp addSubview: addTitleLb];
         
          
        // 右侧
        [addIconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(addRecWarp).offset(12);
            make.centerX.equalTo(addRecWarp);
            make.width.mas_offset(48);
            make.height.mas_offset(57);
        }];
        
        [addTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(addIconView.mas_bottom).offset(13);
            make.left.equalTo(addRecWarp).offset(15);
            make.right.equalTo(addRecWarp).offset(-15);
            make.bottom.equalTo(addRecWarp).offset(-15);
        }];
        [addTitleLb setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];

    }else {
        [dataWarp mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topView);
            make.left.equalTo(topView).offset(20);
            make.right.equalTo(topView).offset(-20);
            make.height.equalTo(@120);
            make.bottom.equalTo(topView).offset(-20);
        }];
    }
      
    
    // 底部视图
    UIView *bottomView = [UIView new];
    bottomView.backgroundColor = KWhiteColor;
    [_contentView addSubview: bottomView];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom).offset(0);
        make.left.equalTo(_contentView);
        make.right.equalTo(_contentView);
        make.bottom.equalTo(_contentView).offset(-15);
    }];
    
    
    NSArray *array = [NSArray arrayWithObjects:@"最近",@"本周",@"月",@"年", nil];
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:array];
    segment.selectedSegmentIndex = 0;
    _segment = segment;
    //设置Segment的字体
    NSDictionary *dic = @{
                           //1.设置字体样式:例如黑体,和字体大小
                           NSFontAttributeName:[UIFont fontWithName:@"Arial-BoldMT" size:20],
                           //2.字体颜色
                           NSForegroundColorAttributeName:[UIColor grayColor]
                           };
    [segment setTitleTextAttributes:dic forState:UIControlStateNormal];
    
    [segment setTitleTextAttributes:[NSDictionary dictionaryWithObject: CNavBgColor forKey:NSForegroundColorAttributeName] forState:UIControlStateNormal];
    [segment setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName] forState:UIControlStateSelected];
    
    [segment setBackgroundImage:[UIImage imageWithColor:KWhiteColor] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [segment setBackgroundImage:[UIImage imageWithColor:CNavBgColor] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    segment.layer.borderColor = CNavBgColor.CGColor;
    segment.layer.borderWidth = 1;
    segment.tintColor = CNavBgColor;
    [bottomView addSubview:segment];
    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
 

    [segment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomView).offset(20);
        make.left.equalTo(bottomView).offset(40);
        make.right.equalTo(bottomView).offset(-40);
        make.height.mas_offset(45);
    }];
    
    [self initChartWithSuperView:bottomView topView:segment];
}
 
- (void)createBigItemWithTopView:(UIView *)topView {
 
    __block UIView *lastView;
    NSArray *items = _model.normalRangs;

    [items enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        UIView *smallItem = [self createItemViewWithModel:obj];
        [self.dataWarp addSubview: smallItem];
 
        [smallItem mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.dataWarp).offset(15);
            make.right.equalTo(self.dataWarp).offset(-15);
            
            if (idx == 0) {
                make.top.equalTo(topView.mas_bottom).offset(15);
            }else {
                make.top.equalTo(lastView.mas_bottom).offset(6);
            }
//            if (idx == (items.count-1)) {
//                make.bottom.equalTo(self.dataWarp).offset(-15);
//            }
        }];
        lastView = smallItem;
    }];
}

// 创建 小项视图 【剂量：1mg/次】
- (UIView *)createItemViewWithModel:(NSDictionary *)model{
    UIView *itemWarp = [UIView new];
 
    // middle
    UILabel *nameTitlLb = [UILabel new];
    nameTitlLb.text = [NSString stringWithFormat:@"%@：", model[@"name"]];
    nameTitlLb.font = DYBlodFont(18);
    nameTitlLb.textColor = CNavLightBlackColor;
    [itemWarp addSubview: nameTitlLb];
    
    // middle
    UILabel *nameLb = [UILabel new];
    nameLb.text = model[@"value"];
    nameLb.font = DYBlodFont(18);
    nameLb.textColor = CNavBgColor;
    [itemWarp addSubview: nameLb];
     
    [self.normalLbs addObject:nameLb];
     
    [nameTitlLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(itemWarp);
        make.left.equalTo(itemWarp);
    }];
    [nameTitlLb setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    
    [nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(itemWarp);
        make.left.equalTo(nameTitlLb.mas_right);
        make.right.bottom.equalTo(itemWarp);
    }];
    
    return itemWarp;
}

- (void)initChartWithSuperView:(UIView *)superView topView:(UIView *)topView {
    
    _chartWarp = [[UIView alloc] initWithFrame: CGRectZero];
    [superView addSubview:_chartWarp];
    
    [_chartWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom).offset(15);
        make.left.equalTo(superView);
        make.right.equalTo(superView);
        make.height.offset(215);
    }];
     
    // 折线图
    _chartView = [[LineChartView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 200)];
    _chartView.backgroundColor = KWhiteColor;
    _chartView.userInteractionEnabled = YES;
    _chartView.delegate = self;
    _chartView.minOffset = 20; // 内边距
    _chartView.chartDescription.enabled = NO;
    _chartView.dragEnabled = YES;
    _chartView.scaleXEnabled = YES;
    _chartView.pinchZoomEnabled = YES;
    _chartView.drawGridBackgroundEnabled = NO;
    [_chartWarp addSubview: _chartView];
    
    // line
    UIView *line = [UIView new];
    line.backgroundColor = CSplitLineColor;
    [superView addSubview:line];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_chartView.mas_bottom).offset(20);
        make.left.equalTo(superView);
        make.right.equalTo(superView);
        make.height.offset(1);
    }];
    
  
    _yValues = @[].mutableCopy;
    _xAixTitles = @[].mutableCopy;
    _lineColors = @[CNavBgColor, KHexColor(@"FFA900")];
 
    if ([_model.check_name isEqualToString:@"血压"]) {
        _chartView.legend.enabled = YES; // 显示图例
        _chartView.legend.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
        _chartView.legend.verticalAlignment = ChartLegendVerticalAlignmentTop;
    }else {
        _chartView.legend.enabled = NO; // 显示图例
    }

    _chartView.doubleTapToZoomEnabled = NO; //是否支持双击缩放
    //高亮点击
    _chartView.highlightPerTapEnabled = YES;
    //没有数据时显示
    _chartView.noDataText = @"没有数据";

    ChartYAxis *leftAxis = _chartView.leftAxis;
    [leftAxis removeAllLimitLines];
    [leftAxis setXOffset:10];  // y轴水平偏移

//    leftAxis.gridLineDashLengths = @[@5.f, @5.f];
    leftAxis.drawZeroLineEnabled = NO;
    leftAxis.drawLimitLinesBehindDataEnabled = YES;
//    leftAxis.drawGridLinesEnabled = NO;//不绘制网格线
    leftAxis.gridColor = CLightGrayColor;
    _chartView.rightAxis.enabled = NO;
    leftAxis.granularityEnabled = YES;
//    leftAxis.labelFont = DYFont(14);


    //[_chartView.viewPortHandler setMaximumScaleY: 2.f];
    //[_chartView.viewPortHandler setMaximumScaleX: 2.f];

//    ChartMarkerImage *marker = [[ChartMarkerImage alloc] init];

    [self setupXAixTitle];

    _chartView.legend.form = ChartLegendFormLine;
    [_chartView animateWithXAxisDuration:2.5];


    ChartXAxis *xAxis = _chartView.xAxis;
//    xAxis.labelFont = DYFont(14);
//    xAxis.axisLineWidth = 1.0/[UIScreen mainScreen].scale;//设置X轴线宽
    xAxis.labelPosition = XAxisLabelPositionBottom;//X轴的显示位置，默认是显示在上面的
    xAxis.drawGridLinesEnabled = NO;//不绘制网格线
//    xAxis.labelCount = 7;// 网格线数量
    xAxis.labelTextColor = KBlackColor;//label文字颜色
    xAxis.granularity = 1;

    [self setData];
    
    
    [self initPieChartWithSuperView:superView topView:line];
}

- (void)initPieChartWithSuperView:(UIView *)superView topView:(UIView *)topView {
    self.pieChartView = [[PieChartView alloc] init];
    self.pieChartView.backgroundColor = KWhiteColor;
    [self.pieChartView setExtraOffsetsWithLeft:30 top:0 right:30 bottom:0];//饼状图距离边缘的间隙
    self.pieChartView.usePercentValuesEnabled = YES;//是否根据所提供的数据, 将显示数据转换为百分比格式
    self.pieChartView.dragDecelerationEnabled = YES;//拖拽饼状图后是否有惯性效果
     [superView addSubview:self.pieChartView];
    
    // 图例
    self.pieChartView.legend.maxSizePercent = 1;//图例在饼状图中的大小占比, 这会影响图例的宽高
    self.pieChartView.legend.formToTextSpace = 5;//文本间隔
    self.pieChartView.legend.font = DYBlodFont(16);//字体大小
    self.pieChartView.legend.textColor = KBlackColor;//字体颜色
    self.pieChartView.legend.form = ChartLegendFormCircle;//图示样式: 方形、线条、圆形
    self.pieChartView.legend.formSize = 16;//图示大小
    self.pieChartView.legend.horizontalAlignment = ChartLegendHorizontalAlignmentCenter;

    self.pieChartView.entryLabelColor = KBlackColor;
    self.pieChartView.entryLabelFont = DYFont(16);

    [self.pieChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom).offset(30);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 300));
        make.bottom.equalTo(superView).offset(-20);
    }];
    
}

#pragma mark - load data

- (void)loadData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:@"healValue" forKey:@"service"];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:_model.check_code forKey:@"check_code"];
    [params setValue:[NSNumber numberWithInteger:_page_number] forKey:@"page_number"];
    [params setValue:IsNotNull(_start_date) forKey:@"start_date"];
    [params setValue:IsNotNull(_end_date) forKey:@"end_date"];
    [params setValue:[NSString stringWithFormat:@"%@", _selectUser.id] forKey:@"id"];
    [dict setValue:params forKey:@"params"];
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KReportData parameters:dict success:^(id  _Nonnull responseObject) {
        [self.scrollView.mj_header endRefreshing];
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.healthModel = [HEHealthDataModel mj_objectWithKeyValues: response.data];
        
        if (self.healthModel.value) {
            HEHealthDataModel *model = [HEHealthDataModel new];
            model.value = self.healthModel.value;
            model.exception = self.healthModel.exception;
            self.healthModel.total = @[model];
        }
        
        NSArray *normalRangeVal = [self.healthModel.range_desc componentsSeparatedByString:@","];
        
        for (int i = 0; i < normalRangeVal.count; i++) {
            NSString *val = normalRangeVal[i];
            UILabel *lb = self.normalLbs[i];
            lb.text = val;
        }
         
        self.xAixTitles = @[].mutableCopy;
        self.yValues = @[].mutableCopy;
        
        NSMutableArray *yValu1 = @[].mutableCopy;
        NSMutableArray *yValu2 = @[].mutableCopy;

        NSArray *datas = [[self.healthModel.result reverseObjectEnumerator] allObjects];
        for (int i = 0; i < datas.count; i++) {
            HEDataManageModel *model = datas[i];
            model.check_unit = self.model.check_unit;
            
            NSString *xTitle = [NSDate timestampToDate:model.create_date formaterMode:NSDateFormaterModeMD];
            [self.xAixTitles addObject: xTitle];
            
            if ([self.model.check_name isEqualToString:@"血压"]) {
                NSArray *vals = [model.check_value componentsSeparatedByString:@"/"];
                [yValu1 addObject:vals.firstObject];
                [yValu2 addObject:vals.lastObject];
            }else {
                [yValu1 addObject:[NSString stringWithFormat:@"%@", model.check_value]];
            }
        }
        if ([self.model.check_name isEqualToString:@"血压"]) {
            [self.yValues addObject: yValu1];
            [self.yValues addObject: yValu2];
        }else {
            [self.yValues addObject: yValu1];
        }

        [self setupXAixTitle];
        [self setData];
         
        [self setPieData];
        
        if (self.healthModel.result.count == 0) {
            [Dialog toastBottom:@"暂无数据"];
        }
        
     } failure:^(NSError * _Nonnull error) {
         [self.scrollView.mj_header endRefreshing];
    }];
}

#pragma 处理折线图数据
- (void)setupXAixTitle {

    ChartIndexAxisValueFormatter *format = [[ChartIndexAxisValueFormatter alloc] initWithValues: _xAixTitles];
    [_chartView.xAxis setValueFormatter:format];
  
    BalloonMarker *marker = [[BalloonMarker alloc]
                             initWithColor: CNavBgColor
                             font: DYFont(14)
                             textColor: UIColor.whiteColor
                             insets: UIEdgeInsetsMake(8.0, 8.0, 20.0, 8.0)
                             xAxisValueFormatter: format
                             yPrefix: [NSString stringWithFormat:@"%@：", _model.check_name]];
    marker.chartView = _chartView;
    marker.minimumSize = CGSizeMake(80.f, 40.f);
    _chartView.marker = marker;
}

- (void)setData
{
  
    NSMutableArray *dataSets = [NSMutableArray array];
    
    double leftAxisMin = 0;
    double leftAxisMax = 0;
    NSArray *names = @[@"舒张压", @"收缩压"];

    NSInteger i = 0;
    for (NSArray *values in _yValues) {
        
        NSMutableArray *yVals = [NSMutableArray array];
        for (int i = 0; i < values.count; i++)
        {
            NSString *valStr = [NSString stringWithFormat:@"%@", values[i]];
            double val = [valStr doubleValue];
            leftAxisMax = MAX(val, leftAxisMax);
            leftAxisMin = MIN(val, leftAxisMax);
            ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:val];
            [yVals addObject:entry];
        }
        
        NSString *lineName = @"";
        if ([_model.check_name isEqualToString:@"血压"]) {
            lineName = names[i];
        }else {
            lineName = _model.check_name;
        }

        LineChartDataSet *dataSet = [[LineChartDataSet alloc] initWithEntries:yVals label: lineName];

        dataSet.mode = LineChartModeCubicBezier;
        dataSet.lineWidth = 2.0f;//折线宽度
        [dataSet setColor:_lineColors[i]]; //折线颜色
        dataSet.drawValuesEnabled = NO;//是否在拐点处显示数据
        dataSet.drawFilledEnabled = YES; // 填充色
        dataSet.fillColor = [_lineColors[i] colorWithAlphaComponent:0.4];
        
    //        dataSet.valueColors = @[self.colorArray[i]];//折线拐点处显示数据的颜色
    //        dataSet.drawSteppedEnabled = NO;//是否开启绘制阶梯样式的折线图
        dataSet.drawCirclesEnabled = YES;//是否绘制拐点
        dataSet.circleRadius = 3.0f;//拐点半径
        dataSet.axisDependency = AxisDependencyLeft;
        dataSet.drawCircleHoleEnabled = YES;//是否绘制中间的空心
        dataSet.circleHoleRadius = 2.0f;//空心的半径
        dataSet.circleHoleColor = KWhiteColor;//空心的颜色
        [dataSet setCircleColor:_lineColors[i]];
        dataSet.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线)
        dataSet.highlightColor = _lineColors[i];
        dataSet.valueFont = [UIFont systemFontOfSize:12];
        
        [dataSets addObject:dataSet];
        i++;
    }
    
//    self.chartView.leftAxis.axisMaximum = leftAxisMax;
//    self.chartView.leftAxis.axisMinimum = leftAxisMin;
    
    LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
    self.chartView.data = nil;
    self.chartView.data = data;
    [self.chartView animateWithXAxisDuration:0.3f];
}


#pragma mark 处理饼图数据
- (void)setPieData{
      
    //每个区块的数据
    NSMutableArray *yVals = [[NSMutableArray alloc] init];
    NSMutableArray *titles = [[NSMutableArray alloc] init];
    NSArray *defColos = @[CNavBgColor, KHexColor(@"22d100"), KHexColor(@"ff8863")];
    NSMutableArray *colors = [[NSMutableArray alloc] init];

    for (HEDataManageModel *model in self.healthModel.total) {
        PieChartDataEntry *entry = [[PieChartDataEntry alloc] initWithValue:model.value label: [NSString stringWithFormat:@"%@%ld次", [HEEnums indicatorsStateToText: model.exception.integerValue], model.value]];
        [yVals addObject:entry];
        [titles addObject:[HEEnums indicatorsStateToText: model.exception.integerValue]];
        
        [colors addObject: defColos[model.exception.integerValue]];
    }
  
     
    //dataSet
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithEntries:yVals label:@""];
    dataSet.drawValuesEnabled = YES;//是否绘制显示数据
    dataSet.colors = colors;//区块颜色
    dataSet.sliceSpace = 0;//相邻区块之间的间距
    dataSet.selectionShift = 8;//选中区块时, 放大的半径
    dataSet.xValuePosition = PieChartValuePositionInsideSlice;//名称位置
    dataSet.yValuePosition = PieChartValuePositionOutsideSlice;//数据位置
    //数据与区块之间的用于指示的折线样式
    dataSet.valueLinePart1OffsetPercentage = 0.85;//折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远
    dataSet.valueLinePart1Length = 0.5;//折线中第一段长度占比
    dataSet.valueLinePart2Length = 0.4;//折线中第二段长度最大占比
    dataSet.valueLineWidth = 1;//折线的粗细
    dataSet.valueLineColor = [UIColor brownColor];//折线颜色
    dataSet.valueTextColor = KBlackColor;
    dataSet.valueFont = DYBlodFont(18);
     
    // 自定义折线label格式
    ChartDefaultValueFormatter *fom = [[ChartDefaultValueFormatter alloc] initWithBlock:^NSString * _Nonnull(double val, ChartDataEntry * _Nonnull entry, NSInteger idx, ChartViewPortHandler * _Nullable handler) {
        return [NSString stringWithFormat:@"%.1f%%", val];
    }];
    [dataSet setValueFormatter:fom];
    
//    ChartLegendEntry *en = [ChartLegendEntry alloc] initWithLabel:<#(NSString * _Nullable)#> form:<#(enum ChartLegendForm)#> formSize:<#(CGFloat)#> formLineWidth:<#(CGFloat)#> formLineDashPhase:<#(CGFloat)#> formLineDashLengths:<#(NSArray<NSNumber *> * _Nullable)#> formColor:<#(UIColor * _Nullable)#>;
//    self.pieChartView.legend setCustomWithEntries:<#(NSArray<ChartLegendEntry *> * _Nonnull)#>
    
    //data
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    [data setValueTextColor: KBlackColor];
    [data setValueFont: DYBlodFont(18)];
    
    
    self.pieChartView.data = nil;
    self.pieChartView.data = data;
    [self.pieChartView animateWithXAxisDuration:0.3f];
}

#pragma mark - click
- (void)segmentAction:(UISegmentedControl *)control{
    KWeakSelf
    switch (control.selectedSegmentIndex) {
        case 0:
        {
            _page_number = 30;
            _start_date = nil;
            _end_date = nil;
            [self.scrollView.mj_header beginRefreshing];
        }
            break;
        case 1:{
            _page_number = 0;
            _start_date = [NSDate getDateWithIntervalTime: -24 * 60 * 60 * 7 formaterMode:NSDateFormaterModeDefault];
            _end_date = [NSDate getNowDay:NSDateFormaterModeDefault];
            [self.scrollView.mj_header beginRefreshing];
            
            [weakSelf.segment setTitle:@"月" forSegmentAtIndex: 2];
            [weakSelf.segment setTitle:@"年" forSegmentAtIndex:3];
        }
            break;
        case 2:{
            _page_number = 0;
            BRDatePickerView *picker = [[BRDatePickerView alloc] initWithPickerMode: BRDatePickerModeYM];
            picker.minDate = [NSDate dateWithString:@"2016-01" format:@"yyyy-MM"];
            picker.maxDate = [NSDate date];
            // 自定义弹框样式
            BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:CNavBgColor];
            picker.pickerStyle = customStyle;
            [picker show];
            
            picker.resultBlock = ^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
                weakSelf.start_date = [NSString stringWithFormat:@"%@-01 00:00:00", selectValue];
                weakSelf.end_date = [NSDate getNowDay:NSDateFormaterModeDefault];
                [weakSelf.scrollView.mj_header beginRefreshing];
                [weakSelf.segment setTitle:[NSString stringWithFormat:@"%ld月", [selectDate month]] forSegmentAtIndex:2];
                [weakSelf.segment setTitle:@"年" forSegmentAtIndex:3];
            };
        }
            break;
        case 3:{
            _page_number = 0;
            BRDatePickerView *picker = [[BRDatePickerView alloc] initWithPickerMode: BRDatePickerModeY];
            picker.minDate = [NSDate dateWithString:@"2016" format:@"yyyy"];
            picker.maxDate = [NSDate date];
            // 自定义弹框样式
            BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:CNavBgColor];
            picker.pickerStyle = customStyle;
            [picker show];
            
            picker.resultBlock = ^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
                weakSelf.start_date = [NSString stringWithFormat:@"%@-01-01 00:00:00", selectValue];
                weakSelf.end_date = [NSDate getNowDay:NSDateFormaterModeDefault];
                [weakSelf.scrollView.mj_header beginRefreshing];
                [weakSelf.segment setTitle:[NSString stringWithFormat:@"%ld年", [selectDate year]] forSegmentAtIndex: 3];
                [weakSelf.segment setTitle:@"月" forSegmentAtIndex: 2];
            };
        }
            break;
        default:
            break;
    }
}

- (void)addRecClick {
    [self submit];
}
 
- (void)submit {
    // 性别
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]init];
    stringPickerView.pickerMode = BRStringPickerComponentMulti;
    stringPickerView.title = _model.check_name;
    stringPickerView.dataSourceArr = [self getPickerData];
    stringPickerView.selectValues = [self getPickerDefualtVal];
    
    KWeakSelf
    stringPickerView.resultModelArrayBlock = ^(NSArray<BRResultModel *> * _Nullable resultModelArr) {
        NSString *value = @"";
        if (resultModelArr.count == 1) {
            BRResultModel *model = resultModelArr.firstObject;
            NSArray *strs = [model.value componentsSeparatedByString:weakSelf.model.check_unit];
            value = strs.firstObject;
        }
        else {
            BRResultModel *model1 = resultModelArr[0];
            BRResultModel *model2 = resultModelArr[1];
            BRResultModel *model3 = resultModelArr[2];

            NSArray *strs1 = [model1.value componentsSeparatedByString:weakSelf.model.check_unit];
            NSArray *strs3 = [model3.value componentsSeparatedByString:weakSelf.model.check_unit];

            value = [NSString stringWithFormat:@"%@%@%@", strs1.firstObject, model2.value, strs3.firstObject];
        }
        
        [weakSelf saveCheckValue: value];
    };
    
    // 自定义弹框样式
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:CNavBgColor];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}

// 保存数据
- (void)saveCheckValue:(NSString *)val {
    
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:val forKey:@"check_value"];
    [params setValue:_model.check_code forKey:@"check_code"];
    [params setValue:_model.check_name forKey:@"check_name"];
    [params setValue:_selectUser.id forKey:@"usid"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KHealthSave parameters:params success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"操作成功"];
            [self.scrollView.mj_header beginRefreshing];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (NSArray *)getPickerData {
    
    NSInteger min = 0;
    NSInteger max = 0;
    NSMutableArray *data = @[].mutableCopy;
    BOOL isOne = NO;

    if ([@"身高" isEqualToString:_model.check_name]) {
        min = 90;
        max = 250;
        isOne = YES;
    }
    else if ([@"体重" isEqualToString:_model.check_name]) {
        min = 20;
        max = 150;
        isOne = YES;
    }
    else if ([@"睡眠" isEqualToString:_model.check_name]) {
        min = 0;
        max = 24;
        isOne = YES;
    }
    else if ([@"呼吸次数" isEqualToString:_model.check_name]) {
        min = 10;
        max = 60;
        isOne = YES;
    }
    else if ([@"血氧" isEqualToString:_model.check_name]) {
        min = 50;
        max = 150;
        isOne = YES;
    }
    else if ([@"静息心率" isEqualToString:_model.check_name]) {
        min = 30;
        max = 220;
        isOne = YES;
    }
    
    if (isOne) {
        NSMutableArray *vals = @[].mutableCopy;
        for (NSInteger i = min; i <= max; i++) {
            [vals addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }
        [data addObject:vals];
    }
    
    if ([@"体温" isEqualToString:_model.check_name]) {
       min = 34;
       max = 43;
       
       NSMutableArray *vals1 = @[].mutableCopy;
       NSMutableArray *vals2 = @[].mutableCopy;
       NSMutableArray *vals3 = @[].mutableCopy;

       for (NSInteger i = min; i <= max; i++) {
           [vals1 addObject:[NSString stringWithFormat:@"%ld", i]];
       }
       [vals2 addObject:@"."];
       for (NSInteger i = 0; i <= 9; i++) {
           [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
       }

       [data addObject:vals1];
       [data addObject:vals2];
       [data addObject:vals3];
   }
    else if ([@"血压" isEqualToString:_model.check_name]) {
        min = 30;
        max = 150;
        
        NSMutableArray *vals1 = @[].mutableCopy;
        NSMutableArray *vals2 = @[].mutableCopy;
        NSMutableArray *vals3 = @[].mutableCopy;

        for (NSInteger i = min; i <= max; i++) {
            [vals1 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }
        [vals2 addObject:@"/"];
        for (NSInteger i = 50; i <= 250; i++) {
            [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }

        [data addObject:vals1];
        [data addObject:vals2];
        [data addObject:vals3];
    }
    else if ([@"血糖" isEqualToString:_model.check_name]) {
        min = 0;
        max = 25;
        
        NSMutableArray *vals1 = @[].mutableCopy;
        NSMutableArray *vals2 = @[].mutableCopy;
        NSMutableArray *vals3 = @[].mutableCopy;

        for (NSInteger i = min; i <= max; i++) {
            [vals1 addObject:[NSString stringWithFormat:@"%ld", i]];
        }
        [vals2 addObject:@"."];
        for (NSInteger i = 0; i <= 9; i++) {
            [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }

        [data addObject:vals1];
        [data addObject:vals2];
        [data addObject:vals3];
    }
    return data;
}

- (NSArray *)getPickerDefualtVal {
    if ([@"身高" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"175%@", _model.check_unit]];
    }
    else if ([@"体重" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"65%@", _model.check_unit]];
    }
    else if ([@"体温" isEqualToString:_model.check_name]) {
        return @[@"36", @"." ,[NSString stringWithFormat:@"5%@", _model.check_unit]];
    }
    else if ([@"睡眠" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"8%@", _model.check_unit]];
    }
    else if ([@"血压" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"70%@", _model.check_unit], @"/", [NSString stringWithFormat:@"120%@", _model.check_unit]];
    }
    else if ([@"血糖" isEqualToString:_model.check_name]) {
        return @[@"7", @"." ,[NSString stringWithFormat:@"0%@", _model.check_unit]];
    }
    else if ([@"呼吸次数" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"20%@", _model.check_unit]];
    }
    else if ([@"血氧" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"95%@", _model.check_unit]];
    }
    else if ([@"静息心率" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"60%@", _model.check_unit]];
    }
    return @[];
}
 
 
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // 布局子控件
    // 设置scrollView约束
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    // 设置参照视图的约束
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
        make.height.mas_greaterThanOrEqualTo(kScreenHeight-ZXNavBarHeight);
    }];
}

#pragma mark - getters
// scrollView
- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.alwaysBounceVertical = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        
        // 添加下拉刷新控件
        KWeakSelf
        _scrollView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self loadData];
         }];
    }
    return _scrollView;
}

// 约束参照视图
- (UIView *)contentView {
    if (_contentView == nil) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = CViewBgColor;
    }
    return _contentView;
}

- (NSMutableArray<UILabel *> *)normalLbs {
    if (!_normalLbs) {
        _normalLbs = @[].mutableCopy;
    }
    return _normalLbs;
}

@end
